package com.sanqing.iframe;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

import com.sanqing.dao.Dao;
import com.sanqing.model.BookType;
import com.sanqing.model.FloatNumberListener;
import com.sanqing.model.*;

// 自定义文档类，限制文本长度
class MyDocument extends PlainDocument {
    private int maxLength;

    public MyDocument(int maxLength) {
        this.maxLength = maxLength;
    }

    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        if (str == null) return;
        if ((getLength() + str.length()) <= maxLength) {
            super.insertString(offs, str, a);
        }
    }
}

// 数字输入监听器
class NumberListener implements KeyListener {
    @Override
    public void keyTyped(KeyEvent e) {
        char c = e.getKeyChar();
        if (!((c >= '0' && c <= '9') ||
                (c == KeyEvent.VK_BACK_SPACE) ||
                (c == KeyEvent.VK_DELETE) ||
                (c == '.' &&!((JTextField) e.getSource()).getText().contains(".")))) {
            e.consume();
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }
}

public class BookAddIFrame extends JInternalFrame {
    // 声明组件为类成员变量，使内部类可以访问
    private JTextField ISBN;
    private JComboBox bookType;
    private JTextField bookName;
    private JTextField writer;
    private JTextField publisher;
    private JTextField translator;
    private JFormattedTextField pubDate;
    private JTextField price;
    private JLabel imageLabel; // 声明图片标签为成员变量
    private JTextField number; // 书籍介绍文本域
    private JTextField language; // 新增：语言文本框

    public BookAddIFrame() {
        super();
        final BorderLayout borderLayout = new BorderLayout();
        getContentPane().setLayout(borderLayout);
        setIconifiable(true);
        setClosable(true);
        setTitle("图书信息添加");
        setBounds(100, 100, 500, 380); // 进一步增大窗口高度

        // 创建中心面板
        final JPanel mainPanel = new JPanel();
        mainPanel.setBorder(new EmptyBorder(5, 10, 5, 10));
        final GridLayout gridLayout = new GridLayout(0, 4);
        gridLayout.setVgap(8); // 适当增大垂直间距
        gridLayout.setHgap(8); // 适当增大水平间距
        mainPanel.setLayout(gridLayout);
        getContentPane().add(mainPanel);

        // 图书编号
        final JLabel ISBNLable = new JLabel();
        ISBNLable.setToolTipText("图书编号：");
        ISBNLable.setText("书号：");
        ISBNLable.setHorizontalAlignment(SwingConstants.RIGHT); // 统一设置为右对齐
        mainPanel.add(ISBNLable);
        ISBN = new JTextField("请输入13位书号", 13);
        ISBN.setDocument(new MyDocument(13));
        ISBN.setColumns(13);
        ISBN.addKeyListener(new ISBNKeyListener());
        ISBN.addFocusListener(new ISBNFocusListener());
        mainPanel.add(ISBN);

        // 图书类别
        final JLabel bookTypeLabel = new JLabel();
        bookTypeLabel.setHorizontalAlignment(SwingConstants.RIGHT); // 统一设置为右对齐
        bookTypeLabel.setText("类别：");
        mainPanel.add(bookTypeLabel);
        bookType = new JComboBox();
        DefaultComboBoxModel bookTypeModel = (DefaultComboBoxModel) bookType.getModel();
        java.util.List<BookType> list = Dao.selectBookCategory();
        for (int i = 0; i < list.size(); i++) {
            BookType booktype = list.get(i);
            Item item = new Item();
            item.setId(booktype.getId());
            item.setName(booktype.getTypeName());
            bookTypeModel.addElement(item);
        }
        mainPanel.add(bookType);

        // 图书名称
        final JLabel bookNameLabel = new JLabel();
        bookNameLabel.setHorizontalAlignment(SwingConstants.RIGHT); // 统一设置为右对齐
        bookNameLabel.setText("书名：");
        mainPanel.add(bookNameLabel);
        bookName = new JTextField(255);
        mainPanel.add(bookName);

        // 作者
        final JLabel writerLabel = new JLabel();
        writerLabel.setHorizontalAlignment(SwingConstants.RIGHT); // 统一设置为右对齐
        writerLabel.setText("作者：");
        mainPanel.add(writerLabel);
        writer = new JTextField(50);
        writer.setDocument(new MyDocument(50));
        mainPanel.add(writer);

        // 出版社
        final JLabel publisherLabel = new JLabel();
        publisherLabel.setHorizontalAlignment(SwingConstants.RIGHT); // 统一设置为右对齐
        publisherLabel.setText("出版社：");
        mainPanel.add(publisherLabel);
        publisher = new JTextField(20);
        publisher.setDocument(new MyDocument(20));
        mainPanel.add(publisher);

        // 译者
        final JLabel translatorLabel = new JLabel();
        translatorLabel.setHorizontalAlignment(SwingConstants.RIGHT); // 统一设置为右对齐
        translatorLabel.setText("译者：");
        mainPanel.add(translatorLabel);
        translator = new JTextField(50);
        translator.setDocument(new MyDocument(50));
        mainPanel.add(translator);

        // 新增：语言
        final JLabel languageLabel = new JLabel();
        languageLabel.setHorizontalAlignment(SwingConstants.RIGHT); // 统一设置为右对齐
        languageLabel.setText("语言：");
        mainPanel.add(languageLabel);
        language = new JTextField();
        language.setDocument(new MyDocument(10)); // 限制语言输入长度为10
        mainPanel.add(language);

        // 出版日期
        final JLabel pubDateLabel = new JLabel();
        pubDateLabel.setHorizontalAlignment(SwingConstants.RIGHT); // 统一设置为右对齐
        pubDateLabel.setText("出版日期：");
        mainPanel.add(pubDateLabel);
        // 初始显示为yyyy-MM-dd格式
        SimpleDateFormat myfmt = new SimpleDateFormat("yyyy-MM-dd");
        pubDate = new JFormattedTextField(myfmt);
        pubDate.setValue(new java.util.Date());
        mainPanel.add(pubDate);

        // 价格
        final JLabel priceLabel = new JLabel();
        priceLabel.setHorizontalAlignment(SwingConstants.RIGHT); // 统一设置为右对齐
        priceLabel.setText("单价：");
        mainPanel.add(priceLabel);
        price = new JTextField();
        price.setDocument(new MyDocument(5));
        price.addKeyListener(new FloatNumberListener());
        mainPanel.add(price);

        // 书籍个数
        final JLabel numberLabel = new JLabel();
        numberLabel.setHorizontalAlignment(SwingConstants.RIGHT); // 统一设置为右对齐
        numberLabel.setText("书籍个数：");
        mainPanel.add(numberLabel);
        
        number= new JTextField();
        number.setDocument(new MyDocument(3));
        number.addKeyListener(new NumberListener());
        mainPanel.add(number);


        // 底部面板
        final JPanel bottomPanel = new JPanel();
        bottomPanel.setBorder(new LineBorder(SystemColor.activeCaptionBorder, 1, false));
        getContentPane().add(bottomPanel, BorderLayout.SOUTH);
        final FlowLayout flowLayout = new FlowLayout();
        flowLayout.setVgap(2);
        flowLayout.setHgap(30);
        flowLayout.setAlignment(FlowLayout.RIGHT);
        bottomPanel.setLayout(flowLayout);

        // 添加按钮
        JButton buttonadd = new JButton();
        buttonadd.addActionListener(new AddBookActionListener());
        buttonadd.setText("添加");
        bottomPanel.add(buttonadd);

        // 关闭按钮
        JButton buttonclose = new JButton();
        buttonclose.addActionListener(new CloseActionLister());
        buttonclose.setText("关闭");
        bottomPanel.add(buttonclose);

        // 顶部图片 - 改进图片自适应显示
        imageLabel = new JLabel();
        ImageIcon bookAddIcon = new ImageIcon("res/login.jpg");
        if (bookAddIcon.getImage() != null) {
            // 调整图片大小以适应标签
            Image scaledImage = bookAddIcon.getImage().getScaledInstance(
                    500, 80, Image.SCALE_SMOOTH);
            imageLabel.setIcon(new ImageIcon(scaledImage));
        } else {
            // 图片加载失败时显示默认文本
            imageLabel.setText("图片加载失败");
        }
        imageLabel.setPreferredSize(new Dimension(500, 80));
        imageLabel.setBorder(new LineBorder(SystemColor.activeCaption, 1, false));
        getContentPane().add(imageLabel, BorderLayout.NORTH);
        imageLabel.setText("图书信息添加");
        setVisible(true);
    }

    // ISBN焦点监听器
    public class ISBNFocusListener extends FocusAdapter {
        @Override
        public void focusLost(FocusEvent e) {
            if (ISBN != null &&!ISBN.getText().trim().isEmpty()) {
                if (!Dao.selectBookInfo(ISBN.getText().trim()).isEmpty()) {
                    JOptionPane.showMessageDialog(null, "添加书号重复！");
                    ISBN.requestFocus();
                }
            }
        }
    }

    // ISBN键盘监听器（限制只能输入数字）
    public class ISBNKeyListener implements KeyListener {
        @Override
        public void keyPressed(KeyEvent e) {
        }

        @Override
        public void keyReleased(KeyEvent e) {
        }

        @Override
        public void keyTyped(KeyEvent e) {
            char c = e.getKeyChar();
            if (!((c >= '0' && c <= '9') ||
                    c == KeyEvent.VK_BACK_SPACE ||
                    c == KeyEvent.VK_DELETE)) {
                e.consume();
            }
        }
    }

    // 关闭按钮监听器
    public class CloseActionLister implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            doDefaultCloseAction();
        }
    }

    // 添加按钮监听器
    public class AddBookActionListener implements ActionListener {
        @Override
        public void actionPerformed(final ActionEvent e) {
            // 数据校验（新增语言字段的校验）
            if (ISBN.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(null, "书号文本框不可以为空");
                ISBN.requestFocus();
                return;
            }

            if (ISBN.getText().trim().length() != 13) {
                JOptionPane.showMessageDialog(null, "书号文本框输入位数为13位");
                ISBN.requestFocus();
                return;
            }

            if (bookName.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(null, "图书名称文本框不可以为空");
                bookName.requestFocus();
                return;
            }

            if (writer.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(null, "作者文本框不可以为空");
                writer.requestFocus();
                return;
            }

            if (pubDate.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(null, "出版日期文本框不可以为空");
                pubDate.requestFocus();
                return;
            }

            if (price.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(null, "单价文本框不可以为空");
                price.requestFocus();
                return;
            }

            // 新增：语言字段的非空校验
            if (language.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(null, "语言文本框不可以为空");
                language.requestFocus();
                return;
            }

            // 数据格式验证
            try {
                // 验证ISBN是否为纯数字
                Long.parseLong(ISBN.getText().trim());
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(null, "书号必须为纯数字");
                ISBN.requestFocus();
                return;
            }

            try {
                // 验证价格格式
                double priceValue = Double.parseDouble(price.getText().trim());
                if (priceValue <= 0) {
                    throw new NumberFormatException();
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(null, "单价必须为大于0的数字");
                price.requestFocus();
                return;
            }

            // 验证日期格式（支持yyyy-MM-dd和yyyy年MM月dd日）
            java.sql.Date dateValue = validateDate(pubDate.getText().trim());
            if (dateValue == null) {
                JOptionPane.showMessageDialog(null, "出版日期格式不正确，支持yyyy-MM-dd或yyyy年MM月dd日");
                pubDate.requestFocus();
                return;
            }

            // 获取表单数据（新增语言字段）
            String ISBNs = ISBN.getText().trim();
            Item selectedItem = (Item) bookType.getSelectedItem();
            if (selectedItem == null) {
                JOptionPane.showMessageDialog(null, "请选择图书类别");
                return;
            }

            Integer bookTypes = selectedItem.getId();
            String bookNames = bookName.getText().trim();
            String writers = writer.getText().trim();
            String translators = translator.getText().trim();
            String publishers = publisher.getText();
            String prices = price.getText().trim();
            Integer numbers = Integer.parseInt(number.getText().trim());
            String languages = language.getText().trim(); // 获取语言信息

            // 执行添加操作（新增语言参数）
            int i = Dao.Insertbook(
                    ISBNs,
                    bookTypes,
                    bookNames,
                    writers,
                    translators,
                    publishers,
                    languages,
                    dateValue,
                    Double.parseDouble(prices),
                    numbers
            );

            if (i == 1) {
                JOptionPane.showMessageDialog(null, "添加成功");
                doDefaultCloseAction();
            } else {
                JOptionPane.showMessageDialog(null, "添加失败，请检查数据");
            }
        }

        // 日期格式验证方法（支持yyyy-MM-dd和yyyy年MM月dd日）
        private java.sql.Date validateDate(String dateStr) {
            if (dateStr == null || dateStr.trim().isEmpty()) {
                return null;
            }

            // 定义支持的日期格式
            String[] patterns = {
                    "yyyy-MM-dd",
                    "yyyy年MM月dd日"
            };

            for (String pattern : patterns) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                    sdf.setLenient(false); // 严格解析日期
                    java.util.Date utilDate = sdf.parse(dateStr.trim());
                    return new java.sql.Date(utilDate.getTime());
                } catch (ParseException e) {
                    // 继续尝试下一个格式
                }
            }

            return null; // 所有格式都不匹配
        }
    }
}